#-------------------------------------------------------------------------------
# BUILD RULES

# linking binary files (exes)

# If the (output) target has /test/ in it, use $(G++) instead of $(GCC) to link. This
# allows our one single C++ compatability test to build properly.
#compiler=$(if $(findstring /test/, $1),$(G++),$(GCC))
compiler=$(G++)

$(call bin_target,%): dep/%$(BINEXT).d
	@$(MKDIR) $(dir $@)
	@$(ECHO) [BIN] Linking \'$@\'
	$(call compiler,$@) $($@_OBJ) $($@_LIB) $($@_XLIB) $(LFLAGS) -o $@


# linking dlls

$(call dll_target,%): dep/%$(DLLEXT).d
	@$(MKDIR) $(dir $@)
	@$(ECHO) [DLL] Linking \'$@\'
ifeq ($(PLATFORM),WIN32)
	dllwrap -q $($@_OBJ) $($@_LIB) $($@_XLIB) $(LFLAGS) -mno-cygwin --output-def $(basename $@).def -o $(basename $@)$(DLLEXT)
endif
ifeq ($(PLATFORM),MACOSX)
	libtool -dynamic  -o $@ $($@_OBJ) $($@_LIB) $($@_XLIB) $(LFLAGS) -lsystem -flat_namespace -undefined suppress
endif
ifeq ($(PLATFORM),LINUX)
	$(GCC) $($@_OBJ) $($@_LIB) $($@_XLIB) $(LFLAGS) -shared -o $@
endif


# lib

$(call lib_target,%): dep/%$(LIBEXT).d
	@$(MKDIR) $(dir $@)
	@$(ECHO) [LIB] Linking \'$@\'
	$(AR) r $@ $($@_OBJ)
ifeq ($(PLATFORM),MACOSX)
	ranlib $@
endif


# some targets may specify additional include directories (for a third-party
# header, for example).They are added to the commandline as -I flags.
target_includes=$(foreach include, $(sort $(INCLUDES)), -I$(include))

# Compile a C file.
obj/$(TYPE)/%.c.o: src/%.c
	@$(MKDIR) $(dir $@)
	@$(ECHO) [SRC] Compiling \'$@\'
	$(GCC) $(C99FLAGS) $(target_includes) -c $< -o $@

obj/$(TYPE)/%.c.o: sr3/%.c
	@$(MKDIR) $(dir $@)
	@$(ECHO) [SRC] Compiling \'$@\'
	$(GCC) $(C99FLAGS) $(target_includes) -c $< -o $@


# Compile a C++ file
obj/$(TYPE)/%.cpp.o: src/%.cpp
	@$(MKDIR) $(dir $@)
	@$(ECHO) [SRC] Compiling \'$@\'
	$(G++) $(CPPFLAGS) $(target_includes) -c $< -o $@

obj/$(TYPE)/%.cpp.o: sr3/%.cpp
	@$(MKDIR) $(dir $@)
	@$(ECHO) [SRC] Compiling \'$@\'
	$(G++) $(CPPFLAGS) $(target_includes) -c $< -o $@


# Compile an Objective C file. (Rare, MacOS only?)
obj/$(TYPE)/%.m.o: src/%.m
	@$(MKDIR) $(dir $@)
	@$(ECHO) [SRC] Compiling \'$@\'
	$(GCC) $(CFLAGS) $(target_includes) -c $< -o $@


# Compile an autogenerated C file. Autogen code is placed in obj/ rather than
# src/ deliberately, as it reduces the chance of it being accidentally modified
# or checked in to the repository. It also makes it easier to nuke autogenerated
# source during a clean.
obj/$(TYPE)/%.c.o: obj/%.c
	@$(MKDIR) $(dir $@)
	@$(ECHO) [GEN] Compiling \'$@\'
	$(GCC) $(C99FLAGS) $(target_includes) -c $< -o $@


# Expand macros in a C++ file (run through the preprocessor)
obj/$(TYPE)/%.cpp.e: src/%.cpp
	@$(MKDIR) $(dir $@)
	@$(ECHO) [SRC] Compiling \'$@\'
	$(G++) -E $(CPPFLAGS) $(target_includes) -c $< -o $@


